package com.mresources.common.utils;


import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;

import java.io.IOException;
import java.util.Map;

public class WebUtil {

    public static final String GET = "GET";
    public static final String POST = "POST";

    private WebUtil() {
    }

    public static boolean visit(String url, boolean... force200) {
        boolean visited = true;
        try {
            HttpResponse response = visitWithResponse(url);
            if (response == null || force200 != null && response.getStatusLine().getStatusCode() != 200) {
                visited = false;
            }
        } catch (IOException ioException) {
            visited = false;
        }
        return visited;
    }

    public static HttpResponse visitWithResponse(String url) throws IOException {
        return visitWithResponse(url, GET, null);
    }

    public static HttpResponse visitWithResponse(String url, String method, Map<String, String> headers) throws IOException {
        return visitWithResponse(url, method, headers, null);
    }

    public static HttpResponse visitWithResponse(String url, String method, Map<String, String> headers, String body) throws IOException {
        if (GET.equals(method)) {
            HttpClient httpClient = HttpClients.createDefault();
            HttpGet get = new HttpGet(url);
            return httpClient.execute(get);
        } else if (POST.equals(method)) {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost post = new HttpPost(url);
            if (headers != null) {
                setHeaders(post, headers);
            }
            if (body != null) {
                post.setEntity(new StringEntity(body));
            }
            return httpClient.execute(post);
        }
        return null;
    }

    private static void setHeaders(HttpPost post, Map<String, String> headers) {
        headers.forEach(post::setHeader);
    }

    public static String visitWithResultString(String url) {
        String result;
        try {
            HttpResponse response = visitWithResponse(url);
            if (response == null) return null;
            result = EntityUtils.toString(response.getEntity());
        } catch (IOException ioException) {
            result = Strings.EMPTY;
        }
        return result;
    }
}
